<template>
  <span>
    <el-button type="primary" @click="addItem">
    添加商品
  </el-button>
  <el-dialog title="添加商品" :visible.sync="dialogAdd" width="55%"
             :destroy-on-close="true" ref="dialog" :before-close="handleClose">
    <el-form ref="form" :model="pageInfo" :rules="rules" label-width="80px">
      <el-row>
        <el-col :span="8" :offset="0">
          <el-form-item prop="productId" label="商品ID:">
            <el-input v-model.trim="pageInfo.productId" size="medium"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="4">
          <el-form-item prop="title" label="商品名称:">
            <el-input v-model.trim="pageInfo.title" size="medium"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="18" :offset="0">
          <el-form-item prop="subjectName" label="商品类目:">
            <el-select v-model="pageInfo.categoryLevel1Id" @change="getCateList(arguments[0],2)"
                       size='medium' placeholder="请选择一级类目" class="w150" clearable>
              <el-option
                v-for="item in cateOptions1"
                :key="item.categoryId"
                :label="item.categoryName"
                :value="item.categoryId">
              </el-option>
            </el-select>
            <el-select v-model="pageInfo.categoryLevel2Id" v-if="cateOptions2.length"
                       @change="getCateList(arguments[0],3)"
                       size='medium' placeholder="请选择二级类目" class="w150">
              <el-option
                v-for="item in cateOptions2"
                :key="item.categoryId"
                :label="item.categoryName"
                :value="item.categoryId">
              </el-option>
            </el-select>
            <el-select v-model="pageInfo.categoryLevel3Id" v-if="cateOptions3.length" size='medium'
                       placeholder="请选择三级类目" class="w150">
              <el-option
                v-for="item in cateOptions3"
                :key="item.categoryId"
                :label="item.categoryName"
                :value="item.categoryId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="0" class="tx-r">
          <el-button type="primary" @click="onSearch" size="medium">搜索</el-button>
          <el-button type="" @click="checkAll" size="medium">{{checkText}}</el-button>
        </el-col>
      </el-row>
    </el-form>
    <!--    商品列表选择-->
    <el-row style="min-height: 300px">
      <el-col v-for="(item,i) in columnData" :span="4" :offset="i%5?1:0" :key="i" class="item-select">
        <div :class="{mask:true,'has-selected':item.hasSelected}"></div>
        <span class="sale-out" v-if="item.totalStock === 0">售罄</span>
        <div @click="!item.hasSelected && itemSelect(item)">
          <div class="mask"></div>
          <el-checkbox size="medium" v-if="!item.hasSelected" v-model="item.checked" class="checkbox"></el-checkbox>
          <el-checkbox v-else v-model="item.hasSelected" class="checkbox" :disabled="item.hasSelected"></el-checkbox>
        <el-row class="image item-image" :style="{'height':`${itemHeight}px`}">
          <img :src="item.mainImage" alt="" :style="{'height':`${itemHeight}px`}">
        </el-row>
        <el-row class="item-title">
          <el-row class="title">
          {{item.title}}
        </el-row>
        <el-row class="price tx-r">
          ￥{{item.salePrice}}
        </el-row>
        </el-row>
          </div>
      </el-col>
    </el-row>
    <!--分页-->
    <el-row>
      <el-col :span="4">
        <el-button type="primary" @click="handleSubmit">{{submitText}}</el-button>
      </el-col>
      <el-col :span="20" class="tx-r">
         <pagination-view  :pagesize="pageInfo.pageSize"
           :currentPage="pageInfo.pageNumber"
           :total="total"
           @size-change="sizeChange"
           @current-change="pageChange"
         ></pagination-view>
      </el-col>
    </el-row>
  </el-dialog>
  </span>
</template>

<script>
  import PaginationView from '@/components/PaginationView'
  import goodsCateApi from '@/api/system/goods/cate'
  import goodsApi from '@/api/goods/goodsManage/commonGoods'
  import pointGoodsApi from '@/api/goods/goodsManage/pointGoods'

  export default {
    name: "index",
    components: {
      PaginationView
    },
    props: {
      type: {type: String, default: "1"},
      searchParam: {
        type: Object
      }
    },
    data() {
      return {
        checkText: '全选',
        itemHeight: '110',
        submitText: '提交',
        columnData: [],
        dialogAdd: false,
        pageInfo: {
          pageNum: 1,
          pageSize: 10,
          categoryLevel1Id: '',
          categoryLevel2Id: '',
          categoryLevel3Id: '',
          productId: '',
          title: '',
          subjectId: ''
        },
        total: 0,
        cateOptions1: [],
        cateOptions2: [],
        cateOptions3: [],
        rules: {},
        selectedItems: [],
        curPageSelect: []
      }
    },
    watch: {
      selectedItems: {
        handler: function (val) {
          console.log(val, 'selectedItems');
          this.submitText = val.length ? `提交(${val.length})` : '提交'
        }
      },
      curPageSelect: {
        handler: function (val) {
          if (val.length) {
            if (val.length === this.columnData.length) {
              this.checkText = '全不选'
            }
          } else {
            this.checkText = '全选'
          }

        }
      },
    },
    methods: {
      handleClose(cb) {
        this.columnData = []
        this.checkText = '全选'
        cb()
      },
      checkAll() {
        if (this.checkText === '全选') {
          this.columnData.map(item => {
            // item['checked'] = true
            this.$set(item, 'checked', true)
            let ifHasPush = false
            if (this.selectedItems.length) {
              this.selectedItems.map(selectItem => {
                if (ifHasPush) return
                if (item.productId === selectItem.productId) {
                  ifHasPush = true
                } else {
                  ifHasPush = false
                }
              })
            }
            if (!ifHasPush) this.selectedItems.push(item)

          })
          this.checkText = '全不选'
        } else {
          this.columnData.map(item => {
            // item['checked'] = false
            this.$set(item, 'checked', false)
            let ifHasDelete = false
            this.selectedItems.map((selectItem, i) => {
              if (ifHasDelete) return
              if (item.productId === selectItem.productId) {
                this.selectedItems.splice(i, 1)
                ifHasDelete = true
              }
            })
          })
          this.checkText = '全选'
        }
      },
      handleSubmit() {
        let checkedItems = []
        this.columnData.map(item => {
          item.checked && checkedItems.push(item)
        })
        this.$emit('select-item', checkedItems)
        this.columnData = []
        this.checkText = '全选'
        this.dialogAdd = false

      },
      findIndex(list, id) {
        let index = ''
        list.map((item, i) => {
          if (item.productId === id)
            return index = i
        })
        return index
      },
      itemSelect(item) {
        console.log(item['checked']);
        if (!item['checked']) {
          item['checked'] = true
          this.selectedItems.push(item)
          this.curPageSelect.push(item)
        } else {
          item['checked'] = false
          this.selectedItems.splice(this.findIndex(this.selectedItems, item.productId))
          this.curPageSelect.splice(this.findIndex(this.curPageSelect, item.productId))
        }
      },
      onSearch() {
        this.pageInfo.pageNumber=1
        this.pageInfo.pageSize=10
        this.getGoodsList()
      },
      addItem() {
        this.dialogAdd = true
        let pageInfoInit={
          pageNum: 1,
            pageSize: 10,
            categoryLevel1Id: '',
            categoryLevel2Id: '',
            categoryLevel3Id: '',
            productId: '',
            title: '',
            subjectId: ''
        }
        this.cateOptions2 = []
        this.cateOptions3 = []
        //组装搜索参数
        this.pageInfo = Object.assign({}, pageInfoInit, this.searchParam)
        this.getGoodsList()
      },
      handleResponse(res) {
        let columnData = res.body.records
        columnData.map(item => {
          this.selectedItems.length ? this.selectedItems.map(selectItem => {
            if (item['checked']) return false
            if (item.productId === selectItem.productId) {
              this.curPageSelect.push(item)
              return item['checked'] = selectItem.checked
            } else {
              return item['checked'] = false
            }
          }) : item['checked'] = false
          if (item.hasSelected) {
            item.hasSelected = true
          }
        })
        this.columnData = columnData
        this.total = Number(res.body.total)
        this.pageInfo.pageNumber = Number(res.body.pageNumber) || 1
        this.handleHeight()
      },
      handleHeight(){
        setTimeout(() => {
          const item = document.getElementsByClassName('item-image')[0];
          this.itemHeight = item.clientWidth
        }, 100)
      },
      getGoodsList() {
        if (this.type === '1' || this.type === '2') {
          goodsApi.getList(this.pageInfo).then(res => {
            this.handleResponse(res)
          })
        } else {
          pointGoodsApi.getList(this.pageInfo).then(res => {
            this.handleResponse(res)
          })
        }

      },
      getCateList(parentId, level) {
        // if (!parentId.toString()) {
          switch (level) {
            case 2:
              this.cateOptions2 = ''
              this.cateOptions3 = ''
              this.pageInfo.categoryLevel2Id =''
              this.pageInfo.categoryLevel3Id =''
              break
            case 3:
              this.cateOptions3 = ''
              this.pageInfo.categoryLevel3Id =''
              break
          }
          // return false
        // }
        goodsCateApi.findByParentId(parentId).then(res => {
          this[`cateOptions${level}`] = res.body
        })
      },
      // pageSize变化函数
      sizeChange(val) {
        this.pageInfo.pageSize = val
        this.columnData = []
        this.checkText = '全选'
        this.curPageSelect = []
        this.getGoodsList()

      },
      // page变化函数
      pageChange(val) {
        this.pageInfo.pageNumber = val
        this.columnData = []
        this.checkText = '全选'
        this.curPageSelect = []
        this.getGoodsList()
      },
    },
    created() {
      this.getCateList(0, 1)
    },
    mounted() {
      let self = this
      console.log(self.searchParam);
      self.pageInfo = Object.assign({}, self.pageInfo, self.searchParam)
      console.log(self.pageInfo,121212);
      window.onresize = function () { // 定义窗口大小变更通知事件
        const item = document.getElementsByClassName('item-image')[0];
        // debugger
        self.itemHeight = item && item.clientWidth
      }
    }
  }
</script>

<style lang="scss" scoped>
  .el-form-item{
    margin-bottom: 10px;
  }
  .w150 {
    width: 150px;
  }

  .item-select {
    border: 1px solid #ddd;
    margin-bottom: 10px;
    position: relative;

    .mask {
      position: absolute;
      width: 100%;
      height: 100%;
      z-index: 1;
      cursor: pointer;
    }

    .has-selected {
      background: rgba(0, 0, 0, .05);
    }

    .sale-out {
      position: absolute;
      padding: 3px 5px;
      font-pageSize: 12px;
      border: 1px solid #ddd;
      z-index: 1;
      right: -1px;
      top: -1px;
      background: #fff;
    }

    .checkbox {
      position: absolute;
      top: 0;
      left: 2px;
    }

    .item-title {
      padding: 5px 5px;

      .title {
        line-height: 20px;
      }
    }

    .image {
      img {
        width: 100%;
      }
    }

    .title {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
</style>
